import { create } from 'zustand'
import {
  ConnectSSH,
  DisconnectSSH,
  StartLogStream,
  StopLogStream,
  GetConnectedSSHHost,
  GetHostInfo,
  CheckCmdIsContinuous,
  DeleteSSHHost,
} from '../../wailsjs/go/main/App'
import { message } from 'antd'

interface SSHConfig {
  username: string
  password: string
  host: string
  port: number
  command: string
  stream: boolean
}

interface SSHState {
  sshConfig: SSHConfig
  logs: string[]
  error: string | null
  isStreaming: boolean
  isConnected: boolean
  hostportList: string[]
  store: boolean
  enableStream: boolean

  // Actions
  setSSHConfig: (config: Partial<SSHConfig>) => void
  setLogs: (logs: string[]) => void
  appendLog: (log: string) => void
  clearLogs: () => void
  setError: (error: string | null) => void
  setIsStreaming: (isStreaming: boolean) => void
  setStore: (store: boolean) => void
  setEnableStream: (enable: boolean) => void

  // API Actions
  connect: () => Promise<void>
  disconnect: () => Promise<void>
  executeCommand: () => Promise<void>
  stopStream: () => Promise<void>
  getHostportList: () => Promise<void>
  getHostInfo: (host: string, port: number) => Promise<any>
  deleteHost: (host: string, port: number) => Promise<void>
}

const initialConfig: SSHConfig = {
  username: 'root',
  password: 'Dell@123',
  host: '192.100.8.26',
  port: 22,
  command: 'docker ps',
  stream: false,
}

export const useSSHStore = create<SSHState>((set, get) => ({
  sshConfig: initialConfig,
  logs: [],
  error: null,
  isStreaming: false,
  isConnected: false,
  hostportList: [],
  store: false,
  enableStream: false,

  // Basic state setters
  setSSHConfig: (config) =>
    set((state) => ({ sshConfig: { ...state.sshConfig, ...config } })),
  setLogs: (logs) => set({ logs }),
  appendLog: (log) => set((state) => ({ logs: [...state.logs, log] })),
  clearLogs: () => set({ logs: [] }),
  setError: (error) => set({ error }),
  setIsStreaming: (isStreaming) => set({ isStreaming }),
  setStore: (store) => set({ store }),
  setEnableStream: (enable) => set({ enableStream: enable }),

  // API Actions
  connect: async () => {
    const state = get()
    const { username, password, host, port } = state.sshConfig

    message.loading('正在连接...', 0)
    try {
      await ConnectSSH(username, password, host, port, state.store)
      set({ isConnected: true })
      message.destroy()
      message.success('服务已建立')
    } catch (error) {
      message.destroy()
      message.error('连接失败')
      console.error('Connect error:', error)
    }
  },

  disconnect: async () => {
    const state = get()
    if (state.isStreaming) {
      message.warning('正在流式传输中, 请先终止流式传输')
      return
    }

    try {
      await DisconnectSSH()
      set({
        isConnected: false,
        isStreaming: false,
        logs: [],
        error: null,
      })
      message.success('服务已断开')
    } catch (error) {
      message.error('断开连接失败')
      console.error('Disconnect error:', error)
    }
  },

  executeCommand: async () => {
    const state = get()
    if (!state.isConnected) {
      message.error('请先建立连接')
      return
    }

    set({ logs: [], error: null, isStreaming: true })

    const startLogStream = async (command: string, stream: boolean) => {
      try {
        await StartLogStream(command, stream)
        if (stream) {
          message.success('流式传输已启动')
        }
      } catch (error) {
        if (stream) {
          message.error('流式传输启动失败')
        } else {
          message.error('命令执行失败')
        }
        console.error('Execute command error:', error)
      }
    }

    try {
      const isContinuous = await CheckCmdIsContinuous(state.sshConfig.command)
      if (isContinuous) {
        set({ enableStream: true })
        state.sshConfig.stream = true
      }
      await startLogStream(state.sshConfig.command, state.sshConfig.stream)
    } catch (error) {
      await startLogStream(state.sshConfig.command, state.sshConfig.stream)
    }
  },

  stopStream: async () => {
    try {
      await StopLogStream()
      set({
        enableStream: false,
        isStreaming: false,
        sshConfig: { ...get().sshConfig, stream: false },
      })
      message.success('流式传输已停止')
    } catch (error) {
      message.error('流式传输停止失败')
      console.error('Stop stream error:', error)
    }
  },

  getHostportList: async () => {
    try {
      const hostportList = await GetConnectedSSHHost()
      set({ hostportList })
    } catch (error) {
      console.error('Get hostport list error:', error)
    }
  },

  getHostInfo: async (host: string, port: number) => {
    try {
      return await GetHostInfo(host, port)
    } catch (error) {
      console.error('Get host info error:', error)
      return null
    }
  },

  deleteHost: async (host: string, port: number) => {
    try {
      await DeleteSSHHost(host, port)
      message.success(`已删除主机记录 ${host}:${port}`)
      // Refresh the host list
      get().getHostportList()
    } catch (error) {
      message.error('删除主机记录失败')
      console.error('Delete host error:', error)
    }
  },
}))
